package cn.tp.ksoft.civil_driver.request;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Map;

import cn.tp.ksoft.civil_driver.R;
import cn.tp.ksoft.civil_driver.bean.ResultBean;
import cn.tp.ksoft.civil_driver.utils.Constants;
import cn.tp.ksoft.civil_driver.utils.SystemPreference;
import cn.tp.ksoft.library_civil.dialog.ProgressFactory;
import cn.tp.ksoft.library_civil.request.Callback;
import cn.tp.ksoft.library_civil.request.OkHttpUtils;
import cn.tp.ksoft.library_civil.request.builder.PostFormBuilder;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * BaseRequest 基础请求
 * @author janlin  2016-3-25
 *
 */
public class BaseRequest {

	protected RequestParams mParams;
	protected Dialog mProgressBar = null;
	protected Handler mHandler;
	protected WeakReference<Context> mContext;

	public BaseRequest(Context context, Handler handler) {
		mHandler = handler;
		mContext = new WeakReference<Context>(context);
	}
	protected boolean checkRecycle() {
		if (mContext == null || null == mContext.get()) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 请求方法
	 * @param callback
	 */
	@SuppressWarnings("rawtypes")
	protected void doRequest(ProgressCall callback) {
		PostFormBuilder builder = OkHttpUtils.post().url(mParams.getURL());
		if(mParams.getParams()!= null){
			Iterator iter = mParams.getParams().entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
				String key = (String) entry.getKey();
				Object val = entry.getValue();
				if(val instanceof File){
					File file = (File) val;
					builder.addFile(key, file.getName(), (File)val);
				}else{
					builder.addParams(key, val==null?"":val.toString());
				}
			}
		}
		builder.addHeader("auth-token", SystemPreference.readSystemValue(mParams.getContext(), SystemPreference.SYSTEM_VALUE_USER_TOKEN, ""));
		builder.build().execute(callback);
	}
	
	public abstract class ProgressCall extends Callback<ResultBean>{

		@Override
		public void onBefore(Request request) {
			// TODO Auto-generated method stub
			super.onBefore(request);
			// 显示进度条
			if(mParams.isShowProgress() && null != mParams.getContext()){
				mProgressBar = ProgressFactory.creatProgress(mParams.getContext(), null);
				mProgressBar.show();
			}
		}

		@Override
		public void onAfter() {
			// TODO Auto-generated method stub
			super.onAfter();
			// 隐藏进度条
			if(null != mProgressBar && mProgressBar.isShowing()){
				mProgressBar.dismiss();
				mProgressBar = null;
			}
		}

		protected ResultBean parseBaseInfo(Response response)
				throws Exception {
			String string = response.body().string();
			JSONObject jsonObj = new JSONObject(string);
			ResultBean user = new ResultBean();
			user.setSuccess(jsonObj.optBoolean("success"));
			user.setTitle(jsonObj.optString("title"));
			user.setDescription(jsonObj.optString("description"));
			user.setKickedOut(jsonObj.optBoolean("kickedOut"));
			user.setData(jsonObj.optString("data"));
			return user;
		}

		@Override
		public ResultBean parseNetworkResponse(Response response)
				throws Exception {
			// TODO Auto-generated method stub
			String string = response.body().string();
	        ResultBean user = new Gson().fromJson(string, ResultBean.class);
	        if(user!=null&&user.isKickedOut()){
				LocalBroadcastManager.getInstance(mParams.getContext())
						.sendBroadcast(new Intent(Constants.FILTER_SUFFIX));
	        }
	        return user;
		}

		@Override
		public void onError(Call call, Exception e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onResponse(ResultBean response) {
			// TODO Auto-generated method stub
			
		}
		
	}

	protected class SimpleProgressCall extends ProgressCall {
		private Handler handler;
		private int what;
		public SimpleProgressCall(Handler handler, int what) {
			this.handler = handler;
			this.what = what;
		}

		@Override
		public void onError(Call call, Exception e) {
			Message message = handler.obtainMessage(what);
			message.sendToTarget();
		}

		@Override
		public void onResponse(ResultBean response) {
			if (null == response && null != mContext.get()) {
				Toast.makeText(mContext.get(), mContext.get().getString(R.string.driver_tip_net_not_reach)
				,Toast.LENGTH_SHORT).show();
			}
			Message message = handler.obtainMessage(what, response);
			message.sendToTarget();
		}
	}
	
}
